package com.zs.test;

import com.zs.pojo.Person;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author ZhouShuang
 * @version 17
 * @Title
 * @date 2025/6/9 上午9:00
 */
public class UseClassField {
    public static void main(String [] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException, NoSuchFieldException {
        //获取Class对象的实例
        Class<?> clzz = Person.class;
        //获取Person类的构造函数
        Constructor<?> constructor = clzz.getDeclaredConstructor();
        //调用Person类的无参构造创建Person类的实例
        Object person = constructor.newInstance();
        //获取Person类的属性
        Field name = clzz.getDeclaredField("name");
        name.setAccessible(true);
        System.out.println("name属性赋值前："+name.get(person));
        name.set(person,"张萧然");
        System.out.println("name属性赋值后："+name.get(person));

        Field age = clzz.getDeclaredField("age");
        age.setAccessible(true);
        System.out.println("age属性赋值前："+age.get(person));
        System.out.println("age属性是一个常量不能重新赋值");

        Field address = clzz.getDeclaredField("address");
        address.setAccessible(true);
        System.out.println("address属性赋值前："+address.get(person));
        address.set(person,"beijing");
        System.out.println("address属性赋值后："+address.get(person));

        Field message = clzz.getDeclaredField("message");
        System.out.println("message属性赋值前："+message.get(person));
        message.set(person,"Hello");
        System.out.println("message属性赋值后："+message.get(person));
    }
}
